package com.example.hand_write_ipc;

import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;

import com.example.ipc.Book;

public abstract class BookListener extends Binder implements IBookListener {

    @Override
    public IBinder asBinder() {
        return this;
    }

    public BookListener() {
        attachInterface(this, DESCRIPTOR);
    }

    public static IBookListener asInterface(IBinder binder) {
        if (binder == null) return null;
        IInterface iInterface = binder.queryLocalInterface(DESCRIPTOR);
        if (iInterface instanceof IBookListener) return (IBookListener) iInterface;
        return new Proxy(binder);
    }

    @Override
    protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
        switch (code) {
            case INTERFACE_TRANSACTION:
                reply.writeString(DESCRIPTOR);
                return true;
            case TRANSACTION_NEW_BOOK_ARRIVAL:
                data.enforceInterface(DESCRIPTOR);
                Book book = data.readTypedObject(Book.CREATOR);
                onNewBookArrival(book);
                reply.writeNoException();
                return true;
        }
        return super.onTransact(code, data, reply, flags);
    }

    private static final class Proxy implements IBookListener {
        private IBinder remote;

        public Proxy(IBinder remote) {
            this.remote = remote;
        }

        public String getInterfaceDescriptor() {
            return DESCRIPTOR;
        }

        @Override
        public IBinder asBinder() {
            return remote;
        }

        @Override
        public void onNewBookArrival(Book book) throws RemoteException {
            Parcel data = Parcel.obtain();
            Parcel reply = Parcel.obtain();
            try {
                data.writeInterfaceToken(getInterfaceDescriptor());
                data.writeTypedObject(book, 0);
                remote.transact(TRANSACTION_NEW_BOOK_ARRIVAL, data, reply, 0);
                reply.readException();
            } finally {
                data.recycle();
                reply.recycle();
            }
        }
    }
}
